<template>
	<view class="elderly-management-page">		
		<!-- 老人信息卡片列表 -->
		<view class="elderly-list">
			<view v-if="loading && membersData.length === 0" class="loading-text">加载中...</view>
			<view v-else-if="elderlyList.length === 0" class="empty-text">暂无老人信息</view>
			<view class="elderly-card" v-for="(elderly, index) in elderlyList" :key="`list-elderly-${elderly.id}-${index}`" @tap="viewElderlyDetails(elderly)">
				<view class="card-header">
					<text class="elderly-name">姓名: {{ elderly.name }}</text>
					<view class="header-actions">
						<view class="action-btn add-record-btn" @tap.stop="addRecord(elderly)">
							<view class="btn-icon">
								<text class="icon-plus">+</text>
							</view>
							<text class="action-text">添加记录</text>
						</view>
						<view class="details-link" @tap.stop="viewElderlyDetails(elderly)">
							<text>详情</text>
							<view class="arrow-icon">></view>
						</view>
					</view>
				</view>
				
				<view class="info-grid">
					<view class="info-row">
						<view class="info-item">
							<text class="info-label">性别</text>
							<text class="info-value">{{ elderly.gender }}</text>
						</view>
						<view class="info-item">
							<text class="info-label">年纪</text>
							<text class="info-value">{{ elderly.age }}</text>
						</view>
						<view class="info-item">
							<text class="info-label">身份证号</text>
							<text class="info-value">{{ elderly.idCard }}</text>
						</view>
					</view>
					<view class="info-row">
						<view class="info-item">
							<text class="info-label">籍贯</text>
							<text class="info-value">{{ elderly.origin }}</text>
						</view>
						<view class="info-item">
							<text class="info-label">婚姻状况</text>
							<text class="info-value">{{ elderly.maritalStatus }}</text>
						</view>
						<view class="info-item">
							<text class="info-label">既往病史</text>
							<text class="info-value">{{ elderly.medicalHistory }}</text>
						</view>
						<view class="info-item">
							<text class="info-label">过敏史</text>
							<text class="info-value">{{ elderly.allergies }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 添加记录弹窗 -->
		<view class="upload-modal" v-if="showRecordModal" @tap="cancelRecord">
			<view class="modal-content" @tap.stop>
				<view class="modal-header">
					<text class="modal-title">添加护理记录</text>
					<view class="close-btn" @tap="cancelRecord">
						<text class="close-icon">×</text>
					</view>
				</view>
				
				<view class="modal-body">
					<!-- 健康指标 -->
					<view class="form-item">
						<text class="form-label">体温</text>
						<input class="form-input" v-model="recordForm.health_temperature" placeholder="请输入体温(如: 36.5°C)" />
					</view>
					
					<view class="form-item">
						<text class="form-label">血压</text>
						<input class="form-input" v-model="recordForm.health_pressure" placeholder="请输入血压(如: 120/80)" />
					</view>
					
					<view class="form-item">
						<text class="form-label">心率</text>
						<input class="form-input" v-model="recordForm.health_rate" placeholder="请输入心率(如: 75)" />
					</view>
					
					<!-- 饮食记录 -->
					<view class="form-item">
						<text class="form-label">早餐</text>
						<input class="form-input" v-model="recordForm.food_morning" placeholder="请输入早餐内容" />
					</view>
					
					<view class="form-item">
						<text class="form-label">午餐</text>
						<input class="form-input" v-model="recordForm.food_noon" placeholder="请输入午餐内容" />
					</view>
					
					<view class="form-item">
						<text class="form-label">晚餐</text>
						<input class="form-input" v-model="recordForm.food_evening" placeholder="请输入晚餐内容" />
					</view>
					
					<!-- 护理信息 -->
					<view class="form-item">
						<text class="form-label">护理标题</text>
						<input class="form-input" v-model="recordForm.title" placeholder="请输入护理标题" />
					</view>
					
					<view class="form-item">
						<text class="form-label">记录时间</text>
						<input class="form-input" v-model="recordForm.record_time" placeholder="请选择记录时间" readonly @tap="showTimePicker" />
					</view>
					
					<view class="form-item">
						<text class="form-label">备注信息</text>
						<textarea class="form-textarea" v-model="recordForm.remark" placeholder="请输入备注信息" />
					</view>
					
					<view class="form-item">
						<text class="form-label">上传图片</text>
						<view class="attachment-area">
							<view class="attachment-item" v-for="(pic, index) in recordForm.pics" :key="index">
								<image class="attachment-thumb" :src="pic" mode="aspectFill" />
								<view class="remove-btn" @tap="removePicture(index)">
									<text class="remove-icon">×</text>
								</view>
							</view>
							<view class="add-attachment" @tap="addPicture" v-if="recordForm.pics.length < 5">
								<text class="add-icon">+</text>
							</view>
						</view>
					</view>
				</view>
				
				<view class="modal-footer">
					<button class="modal-btn cancel" @tap="cancelRecord">取消</button>
					<button class="modal-btn submit" @tap="submitRecord">提交</button>
				</view>
			</view>
		</view>

		<!-- 时间选择器 -->
		<u-datetime-picker
			:show="showDateTimePicker"
			mode="datetime"
			:default-time="currentDateTime"
			@confirm="confirmDateTime"
			@cancel="showDateTimePicker = false"
		></u-datetime-picker>
	</view>
</template>

<script>
import { apiGetElderlyMembers, apiAddElderlyRecord } from '@/request/api.js'

export default {
	data() {
		return {
			// API数据
			membersData: [],
			loading: false,
			currentPage: 1,
			pageSize: 10,
			totalCount: 0,
			hasMore: true,
			// 添加记录弹窗相关
			showRecordModal: false,
			showDateTimePicker: false,
			currentSelectedElderly: null,
			recordForm: {
				member_id: '',
				health_temperature: '',
				health_pressure: '',
				health_rate: '',
				food_morning: '',
				food_noon: '',
				food_evening: '',
				title: '',
				remark: '',
				record_time: '',
				pics: [] // 图片数组
			}
		}
	},
	computed: {
		// 获取当前日期时间
		currentDateTime() {
			const now = new Date();
			const year = now.getFullYear();
			const month = String(now.getMonth() + 1).padStart(2, '0');
			const day = String(now.getDate()).padStart(2, '0');
			const hours = String(now.getHours()).padStart(2, '0');
			const minutes = String(now.getMinutes()).padStart(2, '0');
			const seconds = String(now.getSeconds()).padStart(2, '0');
			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
		},
		// 转换API数据为显示格式
		elderlyList() {
			return this.membersData
				.filter(member => member.name && member.id) // 过滤掉空数据
				.map(member => ({
					id: member.id,
					name: member.name,
					gender: member.sex === 0 ? '女' : '男',
					age: this.calculateAge(member.birthday),
					idCard: member.id_num || '未填写',
					origin: this.getLocation(member.province, member.city, member.area),
					maritalStatus: this.getMaritalStatus(member.marray),
					medicalHistory: member.history || '无',
					allergies: member.mi_history || '无',
					phone: member.phone || '',
					photo: member.photo || '',
					rawMember: member
				}));
		}
	},
	onLoad() {
		// 页面加载时的初始化
		this.loadMembersData();
	},
	onShow() {
		// 页面显示时刷新数据
		this.loadMembersData();
	},
	onPullDownRefresh() {
		// 下拉刷新
		this.loadMembersData().then(() => {
			uni.stopPullDownRefresh();
		});
	},
	onReachBottom() {
		// 上拉加载更多
		if (this.hasMore && !this.loading) {
			this.loadMembersData(true);
		}
	},
	methods: {
		// 加载成员数据
		async loadMembersData(loadMore = false) {
			if (this.loading) return;
			
			try {
				this.loading = true;
				
				// 获取用户信息
				const userInfo = uni.getStorageSync('userInfo');
				if (!userInfo || !userInfo.hasLogin) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}
				
				const requestData = {
					uid: userInfo.uid || '33897', // 使用真实的uid，如果没有则使用默认值
					page: loadMore ? this.currentPage + 1 : 1,
					limit: this.pageSize
				};
				
				const response = await apiGetElderlyMembers(requestData);
				
				if (response.code === 0) {
					if (loadMore) {
						this.membersData = [...this.membersData, ...response.data];
						this.currentPage++;
					} else {
						this.membersData = response.data;
						this.currentPage = 1;
					}
					
					this.totalCount = response.count || 0;
					this.hasMore = response.data.length >= this.pageSize;
				}
			} catch (error) {
				console.error('加载成员数据失败:', error);
				uni.showToast({
					title: '数据加载失败',
					icon: 'none'
				});
			} finally {
				this.loading = false;
			}
		},
		
		// 计算年龄
		calculateAge(birthday) {
			if (!birthday || birthday === '0000-00-00') return '未知';
			const birth = new Date(birthday);
			const today = new Date();
			let age = today.getFullYear() - birth.getFullYear();
			const monthDiff = today.getMonth() - birth.getMonth();
			if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
				age--;
			}
			return age > 0 ? age.toString() : '未知';
		},
		
		// 获取地址信息
		getLocation(province, city, area) {
			const location = [province, city, area].filter(item => item && item.trim()).join('');
			return location || '未填写';
		},
		
		// 获取婚姻状况
		getMaritalStatus(marray) {
			switch (marray) {
				case 1: return '未婚';
				case 2: return '已婚';
				case 3: return '离异';
				case 4: return '丧偶';
				default: return '未知';
			}
		},
		
		// 添加记录
		addRecord(elderly) {
			console.log('点击添加记录，老人信息:', elderly);
			console.log('当前时间:', this.currentDateTime);
			
			this.currentSelectedElderly = elderly;
			this.recordForm = {
				member_id: elderly.id,
				health_temperature: '',
				health_pressure: '',
				health_rate: '',
				food_morning: '',
				food_noon: '',
				food_evening: '',
				title: '',
				remark: '',
				record_time: this.currentDateTime,
				pics: [] // 重置图片数组
			};
			
			console.log('设置弹窗显示状态为true');
			this.showRecordModal = true;
			console.log('弹窗显示状态:', this.showRecordModal);
		},

		// 显示时间选择器
		showTimePicker() {
			this.showDateTimePicker = true;
		},

		// 确认时间选择
		confirmDateTime(e) {
			// e.value 是选择的时间戳，需要转换为格式化字符串
			const date = new Date(e.value);
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			const hours = String(date.getHours()).padStart(2, '0');
			const minutes = String(date.getMinutes()).padStart(2, '0');
			const seconds = String(date.getSeconds()).padStart(2, '0');
			
			this.recordForm.record_time = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			this.showDateTimePicker = false;
		},

		// 提交记录
		async submitRecord() {
			if (!this.validateForm()) {
				return;
			}

			try {
				uni.showLoading({
					title: '提交中...'
				});

				// 构建FormData格式的数据
				const formData = {
					member_id: this.recordForm.member_id,
					health_temperature: this.recordForm.health_temperature,
					health_pressure: this.recordForm.health_pressure,
					health_rate: this.recordForm.health_rate,
					food_morning: this.recordForm.food_morning,
					food_noon: this.recordForm.food_noon,
					food_evening: this.recordForm.food_evening,
					title: this.recordForm.title,
					remark: this.recordForm.remark,
					'pics[]': this.recordForm.pics.length > 0 ? this.recordForm.pics.join('|') : 'http://aa.com/1.png|http://aa.com/2.png',
					record_time: this.recordForm.record_time
				};

				const response = await apiAddElderlyRecord(formData);

				if (response.code === 0) {
					uni.showToast({
						title: '添加成功',
						icon: 'success'
					});
					this.showRecordModal = false;
					// 可以选择刷新数据或跳转到详情页
				} else {
					uni.showToast({
						title: response.msg || '添加失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('添加记录失败:', error);
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
			}
		},

		// 取消添加记录
		cancelRecord() {
			setTimeout(() => {
				this.showRecordModal = false;
				this.currentSelectedElderly = null;
			}, 100);
		},

		// 添加图片
		addPicture() {
			uni.chooseImage({
				count: 5 - this.recordForm.pics.length,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					this.recordForm.pics = this.recordForm.pics.concat(res.tempFilePaths);
				}
			});
		},

		// 移除图片
		removePicture(index) {
			this.recordForm.pics.splice(index, 1);
		},

		// 验证表单
		validateForm() {
			if (!this.recordForm.health_temperature.trim()) {
				uni.showToast({
					title: '请输入体温',
					icon: 'none'
				});
				return false;
			}
			if (!this.recordForm.health_pressure.trim()) {
				uni.showToast({
					title: '请输入血压',
					icon: 'none'
				});
				return false;
			}
			if (!this.recordForm.health_rate.trim()) {
				uni.showToast({
					title: '请输入心率',
					icon: 'none'
				});
				return false;
			}
			if (!this.recordForm.title.trim()) {
				uni.showToast({
					title: '请输入护理标题',
					icon: 'none'
				});
				return false;
			}
			return true;
		},
		
		// 查看老人详情
		viewElderlyDetails(elderly) {
			console.log(elderly);
			uni.navigateTo({
				url: `/pages/elderlyDetails/elderlyDetails?id=${elderly.id}`
			});
		}
	}
}
</script>

<style lang="scss" scoped>
.elderly-management-page {
	min-height: 100vh;
	background: #F5F5F5;
	padding: 15rpx 10rpx;
}

.elderly-list {
	padding: 10rpx 20rpx;
}

.elderly-card {
	background: #FFFFFF;
	border-radius: 16rpx;
	padding: 0;
	margin-bottom: 30rpx;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
	position: relative;
	overflow: hidden;
}

.card-header {
	// background: #3498DB;
	padding: 20rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 0;
}

.header-actions {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.action-btn {
	background: linear-gradient(135deg, #FF7D00 0%, #FF4856 100%);
	padding: 12rpx 20rpx;
	border-radius: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(255, 125, 0, 0.3);
	transition: all 0.2s ease;
}

.add-record-btn {
	display: flex;
	align-items: center;
	gap: 8rpx;
	background: linear-gradient(135deg, #4CAF50 0%, #45A049 100%);
	box-shadow: 0 2rpx 8rpx rgba(76, 175, 80, 0.3);
	position: relative;
	overflow: hidden;
}

.add-record-btn:active {
	transform: scale(0.95);
	box-shadow: 0 1rpx 4rpx rgba(76, 175, 80, 0.4);
}

.add-record-btn::before {
	content: '';
	position: absolute;
	top: 0;
	left: -100%;
	width: 100%;
	height: 100%;
	background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
	transition: left 0.5s ease;
}

.add-record-btn:hover::before {
	left: 100%;
}

.btn-icon {
	width: 32rpx;
	height: 32rpx;
	background: rgba(255, 255, 255, 0.2);
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.icon-plus {
	color: #FFFFFF;
	font-size: 20rpx;
	font-weight: bold;
	line-height: 1;
}

.action-text {
	color: #FFFFFF;
	font-size: 24rpx;
	font-weight: 500;
}

.elderly-name {
	font-size: 32rpx;
	font-weight: bold;
	// color: #FFFFFF;
}

.details-link {
	font-size: 26rpx;
	// color: #FFFFFF;
	opacity: 0.8;
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.arrow-icon {
	width: 24rpx;
	height: 24rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 20rpx;
	font-weight: bold;
}

.info-grid {
	display: flex;
	flex-direction: column;
	gap: 16rpx;
	margin: 20rpx;
	background: linear-gradient(0deg, #ffffff33 0%, #ffffff33 100%), #F9FAFB;
	border-radius: 16rpx;
}

.info-row {
	display: flex;
	gap: 16rpx;
}

.info-row:first-child {
	justify-content: space-between;
}

.info-row:first-child .info-item {
	flex: 1;
}

.info-row:last-child {
	justify-content: space-between;
}

.info-row:last-child .info-item {
	flex: 1;
}

.info-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	text-align: center;
	padding: 12rpx;
	// background: #FFFFFF;
	border-radius: 12rpx;
	// box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.info-label {
	font-size: 24rpx;
	color: #666666;
	margin-bottom: 8rpx;
}

.info-value {
	font-size: 28rpx;
	color: #333333;
	font-weight: 500;
}

/* 加载和空状态样式 */
.loading-text, .empty-text {
	text-align: center;
	padding: 80rpx 40rpx;
	color: #999999;
	font-size: 28rpx;
}

.loading-text {
	color: #666666;
}

/* 上传图文弹窗样式 - 参考activityRecord */
.upload-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: flex-end;
	z-index: 1000;
	animation: fadeIn 0.3s ease-out;
	padding-bottom: env(safe-area-inset-bottom);
	-webkit-overflow-scrolling: touch;
}

.modal-content {
	background: #FFFFFF;
	border-radius: 24rpx 24rpx 0 0;
	width: 100%;
	max-height: 85vh;
	box-shadow: 0 -8rpx 24rpx rgba(0, 0, 0, 0.15);
	position: relative;
	overflow: hidden;
	animation: slideUp 0.3s ease-out;
	display: flex;
	flex-direction: column;
	margin-bottom: env(safe-area-inset-bottom);
}

@keyframes fadeIn {
	from {
		opacity: 0;
	}
	to {
		opacity: 1;
	}
}

@keyframes slideUp {
	from {
		transform: translateY(100%);
	}
	to {
		transform: translateY(0);
	}
}

.modal-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 50rpx 40rpx 30rpx;
	border-bottom: 1rpx solid #E0E0E0;
}

.modal-title {
	font-size: 40rpx;
	font-weight: bold;
	color: #333333;
}

.close-btn {
	width: 70rpx;
	height: 70rpx;
	display: flex;
	justify-content: center;
	align-items: center;
}

.close-icon {
	font-size: 56rpx;
	color: #999999;
}

.modal-body {
	padding: 40rpx;
	flex: 1;
	overflow-y: auto;
	max-height: calc(85vh - 200rpx);
	-webkit-overflow-scrolling: touch;
}

.modal-body .form-item {
	margin-bottom: 40rpx;
}

.modal-body .form-label {
	font-size: 30rpx;
	color: #666666;
	margin-bottom: 20rpx;
	display: block;
}

.modal-body .form-input,
.modal-body .form-textarea {
	width: 100%;
	height: 90rpx;
	border: 1rpx solid #E0E0E0;
	border-radius: 12rpx;
	padding: 0 24rpx;
	font-size: 30rpx;
	color: #333333;
	line-height: 1.5;
	box-sizing: border-box;
	background: #FFFFFF;
}

.modal-body .form-textarea {
	padding: 24rpx;
	min-height: 140rpx;
	height: auto;
	resize: none;
}

.attachment-area {
	display: flex;
	flex-wrap: wrap;
	gap: 24rpx;
	margin-top: 24rpx;
}

.attachment-item {
	position: relative;
	width: 140rpx;
	height: 140rpx;
	border-radius: 12rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.attachment-thumb {
	width: 100%;
	height: 100%;
}

.remove-btn {
	position: absolute;
	top: 10rpx;
	right: 10rpx;
	background: rgba(0, 0, 0, 0.6);
	border-radius: 50%;
	width: 44rpx;
	height: 44rpx;
	display: flex;
	justify-content: center;
	align-items: center;
}

.remove-icon {
	color: #FFFFFF;
	font-size: 26rpx;
	font-weight: bold;
}

.add-attachment {
	width: 140rpx;
	height: 140rpx;
	border: 2rpx dashed #E0E0E0;
	border-radius: 12rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	background: #F8F8F8;
}

.add-icon {
	color: #999999;
	font-size: 56rpx;
	font-weight: bold;
}

.modal-footer {
	display: flex;
	justify-content: space-between;
	padding: 40rpx;
	border-top: 1rpx solid #E0E0E0;
	background: #FFFFFF;
	flex-shrink: 0;
}

.modal-btn {
	width: 45%;
	height: 90rpx;
	border-radius: 45rpx;
	font-size: 34rpx;
	border: none;
	transition: all 0.2s ease;
	min-height: 90rpx;
}

.modal-btn.cancel {
	background: #F5F5F5;
	color: #666666;
	border: 1rpx solid #E0E0E0;
}

.modal-btn.submit {
	background: linear-gradient(135deg, #FF7D00 0%, #FF4856 100%);
	color: #FFFFFF;
}

.modal-btn.cancel:active {
	background: #D0D0D0;
	transform: scale(0.98);
}

.modal-btn.submit:active {
	background: #E66A00;
	transform: scale(0.98);
}
</style>